<?php

namespace App\Modules\LuckDraw\UserTag;

use App\Modules\LuckDraw\Models\DrawLogModel;

class ConsumptionUserTag implements UserTagInterface {
    private $_luckId;
    private $_userId;
    private $_strategyPool;
    public function __construct(int $luckId, int $_userId, object $strategyPool) {
        $this->_luckId = $luckId;
        $this->_userId = $_userId;
        $this->_strategyPool = $strategyPool;
    }

    public function getStrategyPool():?array{
        if (empty($this->_strategyPool)) {
            return [];
        }
        //判断是不是走个人奖池
        if ($this->_isPersonal()) {
            return [$this->_strategyPool->personal->strategy, $this->_strategyPool->personal->pool];
        }
        //获取用户总计抽取了多少次
        $allTotal = $this->getUserPopAllCount();
        //若总抽奖次数少于175时次则进入新配置奖池
        if(isset($this->_strategyPool->newpop)){
            foreach ($this->_strategyPool->newpop as $newPool) {
                if($allTotal >= $newPool->consumption_from && $allTotal < $newPool->consumption_to){
                    return [$newPool->strategy, $newPool->pool];
                }
            }
        }
        
        
        //获取用户消费信息
        $total = $this->_getConsumptionTotalWeek();
        foreach ($this->_strategyPool->common as $strategyPool) {
            if ($total >= $strategyPool->consumption_from && $total < $strategyPool->consumption_to) {
                return [$strategyPool->strategy, $strategyPool->pool];
            }
        }
        return [];
    }

    private function _isPersonal(){
        return in_array($this->_userId, $this->_strategyPool->personal->user_list);
    }

    //获取用户在普通许愿池总共抽取了多少次
    public function getUserPopAllCount(){
        $count = DrawLogModel::query()
            ->where("user_id", $this->_userId)
            ->where("luck_id", $this->_luckId)
            ->sum("draw_num");
        return $count;
    }

    //获取24小时内消费总额
    private function _getConsumptionTotalWeek(){
        return DrawLogModel::query()
            ->where("user_id", $this->_userId)
            ->where("luck_id", $this->_luckId)
            ->where("created_at", ">", date('Y-m-d', strtotime('this week')))
            ->sum("draw_num");
    }
    public function getStrategyAllPool():?array{
        if (empty($this->_strategyPool)) {
            return [];
        }
        $data = [];
        //判断是否有个人奖池
        if (isset($this->_strategyPool->personal)) {
            $data[] = [$this->_strategyPool->personal->strategy, $this->_strategyPool->personal->pool, $this->_strategyPool->personal->user_list,'personal'];
        }
        //获取用户消费信息
        if (isset($this->_strategyPool->common)) {
            foreach ($this->_strategyPool->common as $key => $strategyPool) {
                $data[] = [$strategyPool->strategy, $strategyPool->pool,[],'common'.'|'.$key];
            }
        }

        return $data;
    }

    //获取所有策略的名字
    public function getAllStrategyAndUserIds(){
        //获取更改过的奖品信息
        $allStrategy = [];
        $userList = [];
        //普通
        if(isset($this->_strategyPool->common)){
            foreach ($this->_strategyPool->common as $pool) {
                if (isset($pool->strategy->name)) {
                    $allStrategy[$pool->strategy->name] = 1;
                }
            }
        }

        //个人 这个标签不循环
        if(isset($this->_strategyPool->personal)){
            if (isset($this->_strategyPool->personal->strategy->name)) {
                $allStrategy[$this->_strategyPool->personal->strategy->name] = 1;
            }
            if (isset($this->_strategyPool->personal->user_list)) {
                $userList = array_merge($userList, $this->_strategyPool->personal->user_list);
            }
        }
        return [array_keys($allStrategy),$userList];
    }

    public function getUpdatedUserTagByPoolData(array $newPool): ?array {
        $oldStrategyPool = $this->_strategyPool;
        //获取更改过的奖品信息
        $changedAwards = [];
        foreach ($newPool as $a){
            if (isset($a['old_data'])) {
                $keyOld = sprintf("%s-%s-%s",  $a['old_data']['type'], $a['old_data']['id'], $a['old_data']['time']);
                $keyNew = sprintf("%s-%s-%s",  $a['type'], $a['id'], $a['time']);
                if ($keyOld != $keyNew) {
                    $changedAwards[$keyOld] = $a;
                }
            }
        }

        $needUpdate = false;

        //主要是查看补偿的奖品有没有被改，有被修改的话就更新，没有就算了
        //普通
        if(isset($oldStrategyPool->common)){
            foreach ($oldStrategyPool->common as $pool) {
                if (isset($pool->strategy->ext->awards)) {
                    //对比当前id
                    foreach ($pool->strategy->ext->awards as $award) {
                        $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                        if (isset($changedAwards[$key])) {
                            $award->id = $changedAwards[$key]['id'];
                            $award->type = $changedAwards[$key]['type'];
                            $award->time = $changedAwards[$key]['time'];
                            $award->price = $changedAwards[$key]['price'];
                            $needUpdate = true;
                        }
                    }
                }
            }
        }

        //个人
        if(isset($oldStrategyPool->personal)){
            if (isset($oldStrategyPool->personal->strategy->ext->awards)) {
                //对比当前id
                foreach ($oldStrategyPool->personal->strategy->ext->awards as $award) {
                    $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
                    if (isset($changedAwards[$key])) {
                        $award->id = $changedAwards[$key]['id'];
                        $award->type = $changedAwards[$key]['type'];
                        $award->time = $changedAwards[$key]['time'];
                        $award->price = $changedAwards[$key]['price'];
                        $needUpdate = true;
                    }
                }
            }
        }

        //注册
//        if(isset($oldStrategyPool->register)){
//            foreach ($oldStrategyPool->register as $pool) {
//                if (!empty($pool->strategy->ext)) {
//                    //对比当前id
//                    foreach ($pool->strategy->ext as $award) {
//                        $key = sprintf("%s-%s-%s",  $award->type, $award->id, $award->time);
//                        if (isset($changedAwards[$key])) {
//                            $award->id = $changedAwards[$key]['id'];
//                            $award->type = $changedAwards[$key]['type'];
//                            $award->time = $changedAwards[$key]['time'];
//                            $award->price = $changedAwards[$key]['price'];
//                        }
//                    }
//                }
//            }
//        }

        //返回修改后的数据
        return [$needUpdate, json_encode($oldStrategyPool)];
    }
}
